<template>
  <q-page>
    <div class="container">
      <div class="row q-col-gutter-md">
        <div class="col-12">
          <div id="user-view-chart" style="width: 100%; height: 100%; min-height: 350px" />
        </div>
      </div>
    </div>
  </q-page>
</template>

<script lang="ts">
import { defineComponent, ref } from '@vue/composition-api';
import * as echarts from 'echarts';
import { UserView, UserViewAPI } from 'src/lib/api/statistic/UserView';
import { EChartsType } from 'echarts';

export default defineComponent({
  name: 'UserView',
  setup() {
    const chart = ref<EChartsType>();
    const listData = ref<UserView[]>();
    const xAxis = ref<{ data: string[] }>({
      data: []
    });
    const series = ref<{ name: string, type: string, data: number[] }>({
      name: '独立访问量',
      type: 'line',
      data: []
    });
    return { chart, listData, xAxis, series };
  },
  methods: {
    initUserViewChart: async function() {
      const chartElement = document.getElementById('user-view-chart');
      if (chartElement) {
        const chart = echarts.init(chartElement);
        this.chart = chart;
        chart.showLoading();
        const listData = await UserViewAPI.list();
        listData.sort((a, b) => new Date(a.time).getTime() - new Date(b.time).getTime());
        listData.forEach((v, i, a) => {
          a[i].time = new Date(v.time).toLocaleString();
        })
        this.listData = listData;
        chart.hideLoading();
        this.updateChart(listData.map(i => `${i.time}`), listData.map(i => i.count));
      }
    },
    updateChart(xAxisData: string[], seriesData: number[]): void {
      if (this.chart) {
        this.chart.setOption({
          title: {
            text: '站点独立访问量统计'
          },
          tooltip: {},
          legend: {
            data: ['独立访问量']
          },
          xAxis: {
            data: xAxisData
          },
          yAxis: {},
          series: {
            name: '独立访问量',
            type: 'line',
            data: seriesData
          }
        });
      }
    }
  },
  mounted: async function() {
    await this.initUserViewChart();
  }
});
</script>

<style scoped>

</style>
